package com.company.project.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.ScheduledTaskEntity;
import com.company.project.service.ScheduledTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 定时任务Controller
 */
@Api(tags = "定时任务管理")
@RestController
@RequestMapping("/scheduledTask")
@Slf4j
public class ScheduledTaskController {

    @Autowired
    private ScheduledTaskService scheduledTaskService;

    @ApiOperation(value = "新增定时任务")
    @PostMapping("/add")
    //@SaCheckPermission("scheduledTask:add") // 暂时注释掉权限检查
    public DataResult add(@RequestBody ScheduledTaskEntity entity) {
        try {
            entity.setCreateTime(new Date());
            entity.setUpdateTime(new Date());
            scheduledTaskService.save(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("新增定时任务异常：" + e.getMessage());
            return DataResult.fail("新增失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "删除定时任务")
    @DeleteMapping("/delete/{id}")
    //@SaCheckPermission("scheduledTask:delete") // 暂时注释掉权限检查
    public DataResult delete(@PathVariable Integer id) {
        try {
            scheduledTaskService.removeById(id);
            return DataResult.success();
        } catch (Exception e) {
            log.error("删除定时任务异常：" + e.getMessage());
            return DataResult.fail("删除失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "更新定时任务")
    @PostMapping("/update")
    //@SaCheckPermission("scheduledTask:update") // 暂时注释掉权限检查
    public DataResult update(@RequestBody ScheduledTaskEntity entity) {
        try {
            entity.setUpdateTime(new Date());
            scheduledTaskService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("更新定时任务异常：" + e.getMessage());
            return DataResult.fail("更新失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "分页查询定时任务")
    @PostMapping("/listByPage")
    //@SaCheckPermission("scheduledTask:list") // 暂时注释掉权限检查
    public DataResult listByPage(@RequestBody Map<String, Object> params) {
        try {
            // 安全的类型转换
            Integer pageNum = 1;
            Integer pageSize = 10;
            String taskName = null;
            Integer status = null;
            
            // 处理页码
            Object pageObj = params.get("page");
            if (pageObj != null) {
                if (pageObj instanceof Integer) {
                    pageNum = (Integer) pageObj;
                } else if (pageObj instanceof String) {
                    try {
                        pageNum = Integer.parseInt((String) pageObj);
                    } catch (NumberFormatException e) {
                        log.warn("页码格式错误，使用默认值1: " + pageObj);
                    }
                }
            }
            
            // 处理页大小
            Object limitObj = params.get("limit");
            if (limitObj != null) {
                if (limitObj instanceof Integer) {
                    pageSize = (Integer) limitObj;
                } else if (limitObj instanceof String) {
                    try {
                        pageSize = Integer.parseInt((String) limitObj);
                    } catch (NumberFormatException e) {
                        log.warn("页大小格式错误，使用默认值10: " + limitObj);
                    }
                }
            }
            
            // 处理任务名称
            Object taskNameObj = params.get("taskName");
            if (taskNameObj != null) {
                taskName = taskNameObj.toString();
            }
            
            // 处理状态
            Object statusObj = params.get("status");
            if (statusObj != null) {
                if (statusObj instanceof Integer) {
                    status = (Integer) statusObj;
                } else if (statusObj instanceof String) {
                    try {
                        status = Integer.parseInt((String) statusObj);
                    } catch (NumberFormatException e) {
                        log.warn("状态格式错误，忽略状态过滤: " + statusObj);
                    }
                }
            }

            Page<ScheduledTaskEntity> page = new Page<>(pageNum, pageSize);
            QueryWrapper<ScheduledTaskEntity> wrapper = new QueryWrapper<>();

            if (taskName != null && !taskName.trim().isEmpty()) {
                wrapper.like("task_name", taskName);
            }
            if (status != null) {
                wrapper.eq("status", status);
            }
            // 只查询未删除的记录
            wrapper.eq("deleted", 0);
            // 按创建时间倒序
            wrapper.orderByDesc("create_time");

            IPage<ScheduledTaskEntity> result = scheduledTaskService.page(page, wrapper);
            return DataResult.success(result);
        } catch (Exception e) {
            log.error("查询定时任务异常：" + e.getMessage());
            return DataResult.fail("查询异常：" + e.getMessage());
        }
    }

    @ApiOperation(value = "获取定时任务详情")
    @GetMapping("/detail/{id}")
    //@SaCheckPermission("scheduledTask:detail") // 暂时注释掉权限检查
    public DataResult getDetail(@PathVariable Integer id) {
        try {
            ScheduledTaskEntity entity = scheduledTaskService.getOne(
                new QueryWrapper<ScheduledTaskEntity>()
                    .eq("id", id)
                    .eq("deleted", 0)
            );
            if (entity == null) {
                return DataResult.fail("记录不存在");
            }
            return DataResult.success(entity);
        } catch (Exception e) {
            log.error("获取定时任务详情异常：" + e.getMessage());
            return DataResult.fail("获取详情失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "启用定时任务")
    @PostMapping("/status/enable/{id}")
    //@SaCheckPermission("scheduledTask:status:enable") // 暂时注释掉权限检查
    public DataResult enable(@PathVariable Integer id) {
        try {
            ScheduledTaskEntity entity = new ScheduledTaskEntity();
            entity.setId(id);
            entity.setStatus(1);
            entity.setUpdateTime(new Date());
            scheduledTaskService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("启用定时任务异常：" + e.getMessage());
            return DataResult.fail("启用失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "禁用定时任务")
    @PostMapping("/status/disable/{id}")
    //@SaCheckPermission("scheduledTask:status:disable") // 暂时注释掉权限检查
    public DataResult disable(@PathVariable Integer id) {
        try {
            ScheduledTaskEntity entity = new ScheduledTaskEntity();
            entity.setId(id);
            entity.setStatus(0);
            entity.setUpdateTime(new Date());
            scheduledTaskService.updateById(entity);
            return DataResult.success();
        } catch (Exception e) {
            log.error("禁用定时任务异常：" + e.getMessage());
            return DataResult.fail("禁用失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "批量更新状态")
    @PostMapping("/status/batchUpdateStatus")
    //@SaCheckPermission("scheduledTask:status:batch") // 暂时注释掉权限检查
    public DataResult batchUpdateStatus(@RequestBody Map<String, Object> params) {
        try {
            // 安全的类型转换
            List<Integer> ids = null;
            Integer status = null;
            
            // 处理ID列表
            Object idsObj = params.get("ids");
            if (idsObj instanceof List) {
                List<?> idList = (List<?>) idsObj;
                ids = new ArrayList<>();
                for (Object idObj : idList) {
                    if (idObj instanceof Integer) {
                        ids.add((Integer) idObj);
                    } else if (idObj instanceof String) {
                        try {
                            ids.add(Integer.parseInt((String) idObj));
                        } catch (NumberFormatException e) {
                            log.warn("ID格式错误，跳过: " + idObj);
                        }
                    }
                }
            }
            
            // 处理状态
            Object statusObj = params.get("status");
            if (statusObj != null) {
                if (statusObj instanceof Integer) {
                    status = (Integer) statusObj;
                } else if (statusObj instanceof String) {
                    try {
                        status = Integer.parseInt((String) statusObj);
                    } catch (NumberFormatException e) {
                        log.warn("状态格式错误: " + statusObj);
                        return DataResult.fail("状态格式错误");
                    }
                }
            }

            if (ids == null || ids.isEmpty()) {
                return DataResult.fail("请选择要操作的记录");
            }
            
            if (status == null) {
                return DataResult.fail("状态参数不能为空");
            }

            for (Integer id : ids) {
                ScheduledTaskEntity entity = new ScheduledTaskEntity();
                entity.setId(id);
                entity.setStatus(status);
                entity.setUpdateTime(new Date());
                scheduledTaskService.updateById(entity);
            }

            return DataResult.success();
        } catch (Exception e) {
            log.error("批量更新状态异常：" + e.getMessage());
            return DataResult.fail("批量更新失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "获取所有启用的定时任务")
    @GetMapping("/listEnabled")
    //@SaCheckPermission("scheduledTask:list:enabled") // 暂时注释掉权限检查
    public DataResult listEnabled() {
        try {
            List<ScheduledTaskEntity> list = scheduledTaskService.list(
                new QueryWrapper<ScheduledTaskEntity>()
                    .eq("status", 1)
                    .eq("deleted", 0)
                    .orderByAsc("create_time")
            );
            return DataResult.success(list);
        } catch (Exception e) {
            log.error("获取启用定时任务异常：" + e.getMessage());
            return DataResult.fail("获取失败：" + e.getMessage());
        }
    }
}
